package com.ybe.handler.exchange;

import com.sun.net.httpserver.HttpExchange;
import com.ybe.handler.exchange.annotation.HttpExchangeAnnotation;
import com.ybe.stake.StakeHolder;
import com.ybe.util.CommonUtil;
import com.ybe.util.HttpExchangeUtil;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@HttpExchangeAnnotation
public class HighStakesHandler implements HttpExchangeHandler {


    private static final Pattern HIGHSTAKES_PATH = Pattern.compile("^/(\\d+)/highstakes/?$");

    private static final int TOP_K = 20;

    @Override
    public void handler(HttpExchange exchange){

        String path = exchange.getRequestURI().getPath();
        Matcher m = HIGHSTAKES_PATH.matcher(path);
        if (!m.matches()) {
            return ;
        }
        try {
            int offerId = CommonUtil.parseInt(m.group(1));

            Map<Integer, Integer> perCustomer = StakeHolder.getStakesByOffer().get(offerId);
            if (perCustomer == null || perCustomer.isEmpty()) {
                HttpExchangeUtil.sendText(exchange, 200, ""); // empty string
                return ;
            }
            //使用最小堆 处理数据
            PriorityQueue<Map.Entry<Integer, Integer>> heap =
                    new PriorityQueue<>(Comparator.comparingInt(Map.Entry::getValue)); // min-heap by stake
            for (Map.Entry<Integer, Integer> e : perCustomer.entrySet()) {
                if (heap.size() < TOP_K) {
                    heap.offer(e);
                } else if (e.getValue() > heap.peek().getValue()) {
                    heap.poll();
                    heap.offer(e);
                }
            }
            // 排序
            List<Map.Entry<Integer, Integer>> top = new ArrayList<>(heap);
            top.sort((a, b) -> Integer.compare(b.getValue(), a.getValue()));

            // 构建 CSV: customerId=stake,comma-separated
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < top.size(); i++) {
                Map.Entry<Integer, Integer> e = top.get(i);
                if (i > 0) {
                    sb.append(',');
                }
                sb.append(e.getKey()).append('=').append(e.getValue());
            }
            HttpExchangeUtil.sendText(exchange, 200, sb.toString());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public boolean isMatch(HttpExchange exchange) {
        String path = exchange.getRequestURI().getPath();
        final String method = exchange.getRequestMethod();
        return HIGHSTAKES_PATH.matcher(path).matches() && "GET".equalsIgnoreCase(method);
    }
}
